<template>
	<view class="search-page">
		<!-- 自定义顶部导航 -->
		<view class="custom-navbar">
			<view class="navbar-content">
				<image class="back-icon" src="https://apizx01.sc798.com/Resource/home/left.png" mode="aspectFit" @click="goBack"></image>
				<text class="navbar-title">搜索</text>
				<view class="navbar-placeholder"></view>
			</view>
		</view>
		
		<!-- 搜索区域 -->
		<view class="search-section">
			<view class="search-container">
				<view class="search-input-wrapper">
					<image class="search-icon" src="https://apizx01.sc798.com/Resource/home/search.png" mode="aspectFit"></image>
					<input 
						class="search-input" 
						placeholder="请输入企业名称关键字进行搜索"
						v-model="searchText"
						@input="onSearchInput"
						@focus="onInputFocus"
					/>
					<view class="clear-btn" v-if="searchText" @click="clearSearch">
						<text class="clear-icon">✕</text>
					</view>
				</view>
				<view class="search-btn" @click="performSearch">
					<text class="search-btn-text">搜索</text>
				</view>
			</view>
		</view>
		
		<!-- 最近搜索 -->
		<view class="recent-section" v-if="recentSearches.length > 0 && !hasSearched">
			<view class="section-header">
				<text class="section-title">最近搜索</text>
				<view class="clear-recent" @click="clearRecentSearches">
					<image class="trash-icon" src="https://apizx01.sc798.com/Resource/home/delete.png" mode="aspectFit"></image>
				</view>
			</view>
			<view class="recent-tags">
				<view 
					class="tag-item" 
					v-for="(item, index) in recentSearches" 
					:key="index"
					@click="selectRecentSearch(item)"
				>
					<text class="tag-text">{{ item }}</text>
				</view>
			</view>
		</view>
		
		<!-- 企业快讯 -->
		<view class="news-section" v-if="!hasSearched">
			<view class="section-header">
				<view class="hot-icon">
					<text class="hot-text">HOT</text>
				</view>
				<text class="section-title">企业快讯</text>
			</view>
			
			<!-- 企业排行榜 -->
			<view class="enterprise-list">
				<view 
					class="enterprise-item" 
					v-for="(item, index) in enterpriseList" 
					:key="index"
					@click="selectEnterprise(item)"
				>
					<!-- 主要内容区域 -->
					<view class="enterprise-content">
						<!-- 标题 -->
						<text class="enterprise-title">{{ item.name }}</text>
						
						<!-- 标签区域 -->
						<view class="enterprise-tags">
							<view class="tag-item">
								<text class="tag-text">{{ item.legalPerson }}</text>
							</view>
						</view>
						
						<!-- 来源和日期 -->
						<view class="enterprise-meta">
							<text class="source-text">{{ item.source }}</text>
							<text class="date-text">{{ item.date  }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 搜索结果 -->
		<view class="search-results-section" v-if="hasSearched">
			<!-- 搜索结果统计 -->
			<view class="search-stats">
				<text class="stats-text">共为你找到<text class="stats-number">{{ searchTotal }}</text>家公司</text>
			</view>
			
			<!-- 搜索结果列表 -->
			<scroll-view 
				class="search-results-container"
				scroll-y
				@scrolltolower="loadMoreData"
				:lower-threshold="100"
				:key="searchId"
			>
				<view 
					class="result-card" 
					v-for="(item, index) in searchResults" 
					:key="`${searchText}-${index}`"
					@click="selectEnterprise(item)"
				>
					<!-- 上部分：logo和基本信息 -->
					<view class="card-top">
					<view class="company-logo">
						<image 
							v-if="item.logoUrl && !item.showLogoPlaceholder"
							:src="item.logoUrl" 
							class="logo-image" 
							mode="aspectFit"
							@error="() => handleImageError(item)"
						></image>
						<view 
							v-else
							class="logo-placeholder"
						>
							<text class="logo-text">{{ getCompanyNameFirstChar(item.companyName) }}</text>
						</view>
					</view>
						<view class="company-info">
							<text class="company-name">{{ item.companyName }}</text>
							<view class="company-tags">
								<view class="tag-item" v-for="(tag, tagIndex) in getCompanyTags(item)" :key="tagIndex">
									<text class="tag-text">{{ tag }}</text>
								</view>
							</view>
						</view>
					</view>
					
					<!-- 下部分：详细信息 -->
					<view class="card-bottom">
						<view class="info-item">
							<text class="info-label">法定代表人</text>
							<text class="info-value">{{ item.operName }}</text>
						</view>
						<view class="info-divider"></view>
						<view class="info-item">
							<text class="info-label">成立时间</text>
							<text class="info-value">{{ item.startDate }}</text>
						</view>
						<view class="info-divider"></view>
						<view class="info-item">
							<text class="info-label">注册资本</text>
							<text class="info-value">{{ item.registCapi }}</text>
						</view>
					</view>
				</view>
				
				<!-- 加载更多状态 -->
				<view class="load-more-section" v-if="searchResults.length > 0">
					<view class="load-more-content" v-if="isLoadingMore">
						<text class="load-more-text">正在加载更多...</text>
					</view>
					<view class="load-more-content" v-else-if="!hasMoreData">
						<text class="load-more-text">没有更多数据了</text>
					</view>
					<view class="load-more-content" v-else>
						<text class="load-more-text">上拉加载更多</text>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

// 响应式数据
const searchText = ref('')
const isSearching = ref(false)
const hasSearched = ref(false)
const searchTotal = ref(0)
const searchResults = ref([])
const pageNum = ref(1)
const hasMoreData = ref(true)
const isLoadingMore = ref(false)
const searchId = ref(0) // 用于强制重新渲染
const recentSearches = ref([
	'湖北宏泰集团有限公司',
	'腾讯',
	'华为技术有限',
	'恒大地产',
	'新华',
	'阿里巴巴'
])

// 企业列表数据
const enterpriseList = ref([
	{ name: '湖北宏泰集团有限公司', legalPerson: '曾鑫', date: '2006-03-22', source: '企业信息' },
	{ name: '湖北宏泰集团有限公司', legalPerson: '莉莉丝', date: '2006-03-22', source: '企业信息' },
	{ name: '湖北宏泰集团有限公司', legalPerson: '曾鑫', date: '2006-03-22', source: '企业信息' },
	{ name: '湖北宏泰集团有限公司', legalPerson: '曾鑫', date: '2006-03-22', source: '企业信息' },
])

// 方法
const onSearchInput = (e) => {
	searchText.value = e.detail.value
}

const onInputFocus = () => {
	// 当输入框获得焦点时，如果已经搜索过，则返回到非搜索状态
	if (hasSearched.value) {
		hasSearched.value = false
		console.log('输入框获得焦点，返回到历史搜索状态')
	}
}

const clearSearch = () => {
	searchText.value = ''
}

const performSearch = async (isLoadMore = false) => {
	// 如果传入的是事件对象，则认为是新搜索
	if (typeof isLoadMore === 'object' && isLoadMore !== null) {
		isLoadMore = false
	}
	
	if (searchText.value.trim()) {
		try {
			console.log('=== 开始搜索 ===')
			console.log('搜索文本:', searchText.value.trim())
			console.log('是否为加载更多:', isLoadMore)
			console.log('搜索前的结果数量:', searchResults.value.length)
			console.log('当前hasSearched状态:', hasSearched.value)
			
			// 设置搜索状态
			isSearching.value = true
			hasSearched.value = true
			
			// 如果是加载更多，设置加载状态
			if (isLoadMore) {
				isLoadingMore.value = true
			} else {
				// 新搜索时重置页码和清空结果
				pageNum.value = 1
				hasMoreData.value = true
				searchResults.value = []
				searchId.value++ // 强制重新渲染
				// 不要在这里重置 searchTotal，让API响应来设置
			}
			
			// 添加到最近搜索（仅新搜索时）
			if (!isLoadMore) {
				addToRecentSearches(searchText.value.trim())
			}
			
			const data = {
    county: '',
    entindustry: '',
    entname: searchText.value.trim(),
    entnature: '',
    pageNum: pageNum.value,
    pageSize: 10,
    province: ''
  }
  
  uni.request({
    url: 'https://apizx01.sc798.com/api/proxy/enterprise/search/list',
    method: 'POST',
    data: data,
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: (res) => {
      console.log('API响应:', res)
      console.log('是否为加载更多:', isLoadMore)
      console.log('当前搜索文本:', searchText.value)
      
      // 处理搜索结果
      if (res.data && res.data.code === 200) {
        searchTotal.value = res.data.total || 0
        
        if (isLoadMore) {
          // 加载更多：追加数据
          const newItems = (res.data.rows || []).map(item => ({ ...item, showLogoPlaceholder: false }))
          searchResults.value = [...searchResults.value, ...newItems]
          console.log('加载更多后的结果数量:', searchResults.value.length)
        } else {
          // 新搜索：替换数据
          console.log('=== 新搜索处理 ===')
          console.log('API返回的数据:', res.data.rows)
          searchResults.value = (res.data.rows || []).map(item => ({ ...item, showLogoPlaceholder: false }))
          console.log('设置后的searchResults:', searchResults.value)
          console.log('新搜索后结果数量:', searchResults.value.length)
          console.log('searchId当前值:', searchId.value)
        }
        
        // 检查是否还有更多数据
        const currentTotal = searchResults.value.length
        hasMoreData.value = currentTotal < searchTotal.value
        
        console.log('搜索结果数量:', searchTotal.value)
        console.log('当前显示数量:', currentTotal)
        console.log('是否还有更多数据:', hasMoreData.value)
        
        // 强制触发页面更新
        if (!isLoadMore) {
          // 新搜索完成后强制更新
          setTimeout(() => {
            console.log('强制更新后的结果数量:', searchResults.value.length)
          }, 100)
        }
      } else {
        if (!isLoadMore) {
          searchTotal.value = 0
          searchResults.value = []
        }
        console.log('搜索失败或返回数据格式错误')
      }
    },
    fail: (err) => {
      console.log(err, 'err')
      if (!isLoadMore) {
        searchTotal.value = 0
        searchResults.value = []
      }
    },
    complete: () => {
      // 请求完成，重置状态
      isSearching.value = false
      isLoadingMore.value = false
      
      // 如果成功加载更多，页码+1
      if (isLoadMore) {
        pageNum.value++
      }
    }
  })
			
			
			
		
			
			
		} catch (error) {
			console.error('搜索失败:', error)
			uni.showToast({
				title: '搜索失败，请重试',
				icon: 'none'
			})
		} finally {
			isSearching.value = false
		}
	} else {
		uni.showToast({
			title: '请输入搜索关键词',
			icon: 'none'
		})
	}
}

const addToRecentSearches = (searchTerm) => {
	// 如果已存在，先移除
	const index = recentSearches.value.indexOf(searchTerm)
	if (index > -1) {
		recentSearches.value.splice(index, 1)
	}
	// 添加到开头
	recentSearches.value.unshift(searchTerm)
	// 限制最多保存10个
	if (recentSearches.value.length > 10) {
		recentSearches.value = recentSearches.value.slice(0, 10)
	}
}

const selectRecentSearch = (searchTerm) => {
	searchText.value = searchTerm
	// 自动执行搜索
	performSearch()
}

const clearRecentSearches = () => {
	recentSearches.value = []
}

const getRankIcon = (index) => {
	const icons = [
		'https://apizx01.sc798.com/Resource/home/1.png', // 金牌
		'https://apizx01.sc798.com/Resource/home/2.png', // 银牌  
		'https://apizx01.sc798.com/Resource/home/3.png'  // 铜牌
	]
	return icons[index]
}

const selectEnterprise = (enterprise) => {
	console.log('选择企业:', enterprise)
	// 跳转到企业详情页，传递企业信息
	uni.navigateTo({
		url: `/pages/enterprise-detail/enterprise-detail?enterprise=${encodeURIComponent(JSON.stringify(enterprise))}`
	})
}

// 加载更多数据
const loadMoreData = (event) => {
	if (hasMoreData.value && !isLoadingMore.value && searchText.value.trim()) {
		performSearch(true) // 传入 true 表示加载更多
	}
}

const goBack = () => {
	uni.navigateBack()
}

// 获取公司标签
const getCompanyTags = (item) => {
	const tags = []
	if (item.status) {
		tags.push(item.status)
	}
	if (item.industryName) {
		tags.push(item.industryName)
	}
	return tags
}

// 获取公司名称第一个字符
const getCompanyNameFirstChar = (companyName) => {
	if (!companyName) return '企'
	return companyName.charAt(0)
}

// 图片加载错误处理
const handleImageError = (item) => {
	console.log('图片加载失败，企业名称:', item.companyName)
	// 设置该企业项显示占位符
	item.showLogoPlaceholder = true
}

// 生命周期
onMounted(() => {
	console.log('搜索页面已挂载')
})
</script>

<style lang="scss" scoped>
.search-page {
	min-height: 100vh;
	background-color: #ffffff;
	padding-bottom: 100rpx;
}

.custom-navbar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 1000;
	background-color: #ffffff;
	
	.navbar-content {
		display: flex;
		align-items: center;
		height: 210rpx;
		padding: 0 24rpx;
		padding-top: 44rpx;
		box-sizing: border-box;
		
		.back-icon {
			width: 48rpx;
			height: 48rpx;
		}
		
		.navbar-title {
			flex: 1;
			text-align: center;
			font-family: 'Alibaba PuHuiTi', sans-serif;
			font-weight: 500;
			font-size: 32rpx;
			color: #000000;
		}
		
		.navbar-placeholder {
			width: 32rpx;
			height: 32rpx;
		}
	}
}

.search-section {
	padding: 0 24rpx;
	margin-top: 210rpx; // 导航栏高度
	
	.search-container {
		display: flex;
		align-items: center;
		gap: 16rpx;
		
		.search-input-wrapper {
			flex: 1;
			height: 64rpx;
			background-color: #f5f5f5;
			border-radius: 8rpx;
			display: flex;
			align-items: center;
			padding: 0 20rpx;
			
			.search-icon {
				width: 32rpx;
				height: 32rpx;
				margin-right: 16rpx;
			}
			
			.search-input {
				flex: 1;
				font-size: 28rpx;
				color: #333;
				border: none;
				background: transparent;
				
				&::placeholder {
					color: #999;
				}
			}
			
			.clear-btn {
				width: 32rpx;
				height: 32rpx;
				border-radius: 50%;
				background-color: #ccc;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-left: 16rpx;
				
				.clear-icon {
					font-size: 20rpx;
					color: #fff;
				}
			}
		}
		
		.search-btn {
			width: 96rpx;
			height: 56rpx;
			background-color: #296AFD;
			border-radius: 8rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			
			.search-btn-text {
				font-size: 28rpx;
				color: #fff;
				font-weight: 500;
			}
		}
	}
}

.recent-section {
	padding: 0  24rpx 0 24rpx;
	
	box-sizing: border-box;
	.section-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-top: 40rpx;
		margin-bottom: 40rpx;
		
		.section-title {
			font-size: 32rpx;
			font-weight: 600;
			color: #000;
		}
		
		.clear-recent {
			.trash-icon {
				width: 32rpx;
				height: 32rpx;
			}
		}
	}
	
	.recent-tags {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
		
		.tag-item {
			height: 60rpx;
			background-color: #f5f5f5;
			border-radius: 30rpx;
			padding: 0 24rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			
			.tag-text {
				font-size: 26rpx;
				color: #333;
			}
		}
	}
}

.news-section {
	width: 704rpx;
	margin: 48rpx auto 40rpx auto;
	padding: 24rpx;
	background: linear-gradient( 180deg, rgba(43,111,234,0.1) 0%, rgba(255,255,255,0) 100%);
	box-shadow: 0rpx 4rpx 16rpx 0rpx rgba(0,0,0,0.3);
	border-radius: 8rpx;
	box-sizing: border-box;
	.section-header {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
		
		.hot-icon {
			width: 60rpx;
			height: 32rpx;
			background-color: #ff4444;
			border-radius: 4rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-right: 16rpx;
			
			.hot-text {
				font-size: 20rpx;
				color: #fff;
				font-weight: bold;
			}
		}
		
		.section-title {
			font-size: 32rpx;
			font-weight: 600;
			color: #000;
		}
	}
	
	.enterprise-list {
		.enterprise-item {
			
			
			padding: 24rpx;
			margin-bottom: 16rpx;
			
			
			&:last-child {
				margin-bottom: 0;
			}
			
			.enterprise-content {
				.enterprise-title {
					font-weight: 400;
font-size: 28rpx;
color: #000000;
					line-height: 1.4;
					display: block;
					margin-bottom: 16rpx;
				}
				
				.enterprise-tags {
					margin-bottom: 16rpx;
					
					.tag-item {
						display: inline-flex;
						align-items: center;
						justify-content: center;
						background: #FFFFFF;
						border-radius: 8rpx;
						border: 1px solid #EBECEE;
						padding: 6rpx 15rpx;
						height: 32rpx;
						box-sizing: border-box;
						.tag-text {
							font-weight: 400;
font-size: 20rpx;
color: #296AFD;
						}
					}
				}
				
				.enterprise-meta {
					display: flex;
					align-items: center;
					
					
					.source-text {
						font-size: 24rpx;
						color: #666666;
					}
					
					.date-text {
						font-size: 24rpx;
						color: #999999;
						margin-left: 14rpx;
					}
				}
			}
		}
	}
}

// 搜索结果样式
.search-results-section {
	.search-stats {
		margin-top: 35rpx;
		margin-left: 24rpx;
		margin-bottom: 35rpx;
		
		.stats-text {
			font-weight: 400;
			font-size: 25rpx;
			color: #282828;
			
			.stats-number {
				color: #FF0000;
			}
		}
	}
	
	.search-results-container {
		width: 100%;
		background: #EEEFF3;
		padding: 38rpx 0;
		height: calc(100vh - 200rpx);
		
		.result-card {
			width: 687rpx;
			height: auto;
			background: #FFFFFF;
			border-radius: 20rpx;
			margin: 0 auto 25rpx auto;
			padding: 28rpx;
			box-sizing: border-box;
			
			&:last-child {
				margin-bottom: 0;
			}
			
			.card-top {
				display: flex;
				align-items: center;
				margin-bottom: 28rpx;
				
				.company-logo {
					width: 90rpx;
					height: 90rpx;
					background: #fff;
					border-radius: 10rpx;
					border: 1px solid #EEEFF3;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-right: 17rpx;
					
					.logo-image {
						width: 100%;
						height: 100%;
					}
					
					.logo-placeholder {
						width: 100%;
						height: 100%;
						background: #296AFD;
						border-radius: 10rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						
						.logo-text {
							font-family: 'Alibaba PuHuiTi', sans-serif;
							font-weight: 600;
							font-size: 32rpx;
							color: #FFFFFF;
						}
					}
				}
				
				.company-info {
					flex: 1;
					
					.company-name {
						font-weight: 400;
						font-size: 30rpx;
						color: #282828;
						margin-bottom: 19rpx;
						display: block;
					}
					
					.company-tags {
						display: flex;
						flex-wrap: wrap;
						gap: 17rpx;
						
						.tag-item {
							height: 32rpx;
							background: #E6EFFF;
							border-radius: 8rpx;
							border: 1px solid #EBECEE;
							padding: 6rpx 12rpx;
							box-sizing: border-box;
							display: flex;
							align-items: center;
							justify-content: center;
							
							.tag-text {
								font-size: 20rpx;
								color: #296AFD;
							}
						}
					}
				}
			}
			
			.card-bottom {
				display: flex;
				align-items: center;
				justify-content: space-between;
				
				.info-item {
					flex: 1;
					display: flex;
					flex-direction: column;
					align-items: center;
					gap: 19rpx;
					
					.info-label {
						font-weight: 400;
						font-size: 22rpx;
						color: #9B9B9B;
					}
					
					.info-value {
						font-weight: 400;
						font-size: 22rpx;
						color: #000000;
					}
				}
				
				.info-divider {
					width: 1rpx;
					height: 42rpx;
					background: #F2F3F5;
					margin: 0 20rpx;
				}
			}
		}
		
		// 加载更多状态样式
		.load-more-section {
			width: 100%;
			padding: 20rpx 0;
			display: flex;
			justify-content: center;
			align-items: center;
			
			.load-more-content {
				.load-more-text {
					font-family: 'Alibaba PuHuiTi', sans-serif;
					font-weight: 400;
					font-size: 24rpx;
					color: #999999;
				}
			}
		}
	}
}
</style>
